# -*- coding: utf-8 -*-
#   自定义LineEdit类
# @Time    ： 2023/2/16  16:59
# @Auther  ： 徐良
# File     :  lineEditParts.py
from typing import Dict, Any
from PySide6.QtWidgets import QLineEdit
from PySide6.QtGui import QDoubleValidator, QIntValidator
from PySide6.QtGui import QRegularExpressionValidator
from PySide6.QtCore import QRegularExpression


class LineEditBase(QLineEdit):
    """
    基本编辑框
    """
    def __init__(self, parent=None):
        super().__init__(parent)


# region 适合网格的行编辑
class BodyLineEditInt(LineEditBase):
    """
    输入整数型
    """
    def __init__(self, parent=None):
        super(BodyLineEditInt, self).__init__(parent)
        # 创建整数校验器
        validator = QIntValidator(self)
        # 将整数校验器应用于QLineEdit
        self.setValidator(validator)


class BodyLineEditFloat(LineEditBase):
    """
    输入浮点数
    """
    def __init__(self, decimals=2, parent=None):
        super().__init__(parent)

        # 创建浮点数校验器
        self.validator = QDoubleValidator(self)
        self.validator.setDecimals(decimals)  # 设置小数位数

        # 将浮点数校验器应用于QLineEdit
        self.setValidator(self.validator)

    def setDecimals(self, decimals):
        # 设置小数位数
        self.validator.setDecimals(decimals)


class BodyLineEditStr(LineEditBase):
    """
    输入任意字符
    """
    def __init__(self, parent=None):
        super().__init__(parent)

# endregion


# region 适合表单的行编辑
class LineEditStr(LineEditBase):
    """
    form表达使用的lineEdit,允许输入任何字符
    """
    def __init__(self, parent=None):
        super().__init__(parent)

class LineEditInt(LineEditBase):
    """
    form表达使用的lineEdit,允许输入整数，NEG默认为0不允许负整数，1允许负整数
    """
    def __init__(self, parent=None):
        super().__init__(parent)
        self.NEG = 0  # 默认不允许负整数
        if parent and isinstance(parent, dict) and 'NEG' in parent:  # 检查parent是否为字典，并包含NEG键
            self.NEG = int(parent['NEG'])  # 从字典中获取NEG的值
        self.setup_validator()  # 设置输入验证器



    def setup_validator(self):
        """根据 NEG 的值设置输入验证器"""
        if self.NEG == 1:
            # 允许正整数和负整数
            validator = QRegularExpressionValidator(QRegularExpression(r"-?\d*"), self)
        else:
            # 只允许正整数
            validator = QRegularExpressionValidator(QRegularExpression(r"\d*"), self)
        self.setValidator(validator)

    def setNEG(self, value):
        """设置 NEG 的值并更新验证器"""
        if self.NEG != value:
            self.NEG = value
            self.setup_validator()

class LineEditDecimal(LineEditBase):
    """
    form表达使用的lineEdit,允许输入带小数点的数据，默认是2位，根据DP值确定小数位数
    """
    def __init__(self, parent=None):
        super().__init__(parent)
        self.DP = 2  # 默认小数位数是2位
        if parent and isinstance(parent, dict) and 'DP' in parent:  # 检查parent是否为字典，并包含DP键
            self.DP = self.validate_DP(parent['DP'])  # 从字典中获取DP的值，并验证
        self.setup_validator()  # 设置输入验证器

    @staticmethod
    def validate_DP(dp):
        """验证DP的值是否合法，如果不合法则返回默认值2"""
        try:
            dp = int(dp)
            if dp < 0:  # 如果DP为负数，则使用默认值
                return 2
            return dp
        except (ValueError, TypeError):  # 如果DP不是整数，则使用默认值
            return 2

    def setup_validator(self):
        """根据DP的值设置输入验证器"""
        # 使用正则表达式限制输入内容
        regex = QRegularExpression(rf"^-?\d*\.?\d{{0,{self.DP}}}$")
        validator = QRegularExpressionValidator(regex, self)
        self.setValidator(validator)

    def set_dp(self, dp: Dict[str, Any]):
        """设置DP的值并更新验证器"""
        validated_dp = self.validate_DP(dp)
        if self.DP != validated_dp:
            self.DP = validated_dp
            self.setup_validator()

# endregion